package com.sxftech.project.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017/11/7 0007.
 */
@Configuration
@EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {



    @Override
    public void configure(WebSecurity web) throws Exception {
        List<String> ignoringArr = Arrays.asList(new String[]{
                "/**/*.js","/**/*.ico","/**/*.woff","/**/*.json", "/**/*.map",
                "/**/*.css","/**/*.jpg","/**/*.png","/**/*.gif",
                "/resources/**, /webjars/**","/error","/developer/**", "/login"
        });
        String []igs = (String [])ignoringArr.toArray(new String[]{});
        web.ignoring().antMatchers( igs);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**")//.anonymous().disable()
                .authorizeRequests().antMatchers( "/login","/logout").permitAll()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .requestMatchers(CorsUtils::isCorsRequest).permitAll()
                .anyRequest().authenticated()
                .and()
                // 下面是基于Http头的csrf`保护，这部分是可选配置
                .csrf()//.disable()//.authorizeRequests()//.anyRequest()//.permitAll()
                .csrfTokenRepository(csrfTokenRepository()).and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
                // 可选配置结束
                .logout().logoutUrl("/logout").permitAll()
                .and();//.addFilterBefore(sso(), BasicAuthenticationFilter.class)
//                .sessionManagement().sessionFixation().changeSessionId()
//                .maximumSessions(1).expiredUrl("/login");
            ;
//        http.addFilterAfter(getAfterBean(),FilterSecurityInterceptor.class);
//                // 退出成功后，跳转到/路径。
//                .logoutSuccessUrl("/");
    }

//    private Filter sso() {
//        OAuth2ClientAuthenticationProcessingFilter githubFilter
//                = new OAuth2ClientAuthenticationProcessingFilter("/login");
//        OAuth2RestTemplate template = new OAuth2RestTemplate(details, oauth2ClientContext);
//        githubFilter.setRestTemplate(template);
////        githubFilter.setTokenServices(new UserInfoTokenServices(details.getUserInfoUri(), details.getClientId()));
//        return githubFilter;
//    }

    @Bean
    public FilterRegistrationBean oauth2ClientFilterRegistration(
            OAuth2ClientContextFilter filter) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(filter);
        registration.setOrder(-100);
        return registration;
    }

//
//    private Filter getAfterBean(){
//        AuthFilterSecurityInterceptor filter = new AuthFilterSecurityInterceptor();
//        filter.setAuthenticationManager(providerManager);
//        filter.setAccessDecisionManager(new AuthAccessDecisionManagerBean());
//        AuthSecurityMetadataSource metadataSource = new AuthSecurityMetadataSource();
//        metadataSource.setService(new DefaultResourceService(new DefaultResourceCacheService()));
//        filter.setSecurityMetadataSource(metadataSource);
//        return filter;
//    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request
                        .getAttribute(CsrfToken.class.getName());
                if (csrf != null) {
                    Cookie cookie = new Cookie("XSRF-TOKEN", csrf.getToken());
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
                Cookie cookie2 = new Cookie("SESSION",request.getSession().getId());
                System.out.println("============================================" );
                System.out.println("session is:" + request.getSession().getId());
                filterChain.doFilter(request, response);
            }
        };
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }

}
